package com.java.module.chat.util.netty;

import com.google.common.base.Objects;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.Attribute;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ChatHandler
 * 
 * @author yilabao
 * @date 2021年9月28日
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger LOG = LoggerFactory.getLogger(ChatHandler.class);

    /**
     * 存储连接
     */
    private static final ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws Exception {
        Channel channel = ctx.channel();
        if (!CHANNELS.contains(channel)) {
            sendErrorMsg(channel, "INVALID_CHANNEL");
            return;
        }
        LOG.info("【qchat】收到消息：uid：{} 内容：{}", getUid(channel), textFrame.text());
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        CHANNELS.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNELS.remove(channel);
        Long uid = getUid(channel);
        LOG.info("【qchat】用户离线 uid：{} 当前人数：{}", uid, CHANNELS.size());
    }

    public static void login(ChannelHandlerContext ctx, Long uid) {
        LOG.info("【qchat】用户上线 uid：{} 当前人数：{}", uid, CHANNELS.size());
    }

    public static void sendMsg(Long toUid, String msg) {
        Boolean isNot= false;
        for (Channel channel : CHANNELS) {
            System.out.println(getUid(channel)+"=="+toUid);
            if (Objects.equal(getUid(channel), toUid)) {
                isNot = true;
                System.out.println("发送消息成功");
                sendMsg(channel, msg);
            }
        }
        if(!isNot){

        }
    }

    public static boolean isOnline(Long uid) {
        boolean online = false;
        for (Channel channel : CHANNELS) {
            if (Objects.equal(getUid(channel), uid)) {
                online = true;
                break;
            }
        }
        return online;
    }

    private static Long getUid(Channel channel) {
        Attribute<Long> uidAttr = channel.attr(HttpRequestHandler.CHANNEL_USER_KEY);
        if (uidAttr == null) {
            return null;
        }
        Long uid = uidAttr.get();
        if (uid == null) {
            return null;

        }
        return uid;
    }

    private static void sendMsg(Channel channel, String text) {
        channel.writeAndFlush(new TextWebSocketFrame(text));
    }

    private static void sendErrorMsg(Channel channel, String text) {
        sendMsg(channel, text);
    }

}